package StudyCode.summary.BufferAndChannel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class CreateAsynchronousServerSocketChannel {
	public static void main(String[] args) {
		try (AsynchronousServerSocketChannel asynChannel = AsynchronousServerSocketChannel
				.open()) {
			if (asynChannel.isOpen()) {
				asynChannel.setOption(StandardSocketOptions.SO_RCVBUF, 4 * 1024);
				asynChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
				asynChannel.bind(new InetSocketAddress("127.0.0.1", 5555));
				System.out.println("等待连接 ...");
				while (true) {
					Future<AsynchronousSocketChannel> asynFuture = asynChannel.accept();
					try (AsynchronousSocketChannel asyncSocketChannel = asynFuture.get()) {
						System.out.println("连接请求: " + asyncSocketChannel.getRemoteAddress());

						final ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
						while (asyncSocketChannel.read(buffer).get() != -1) {
							buffer.flip();
							asyncSocketChannel.write(buffer).get();
							if (buffer.hasRemaining()) {
								buffer.compact();
							} else {
								buffer.clear();
							}
						}
						System.out.println(asyncSocketChannel.getRemoteAddress() + " 成功送达");
					} catch (IOException | InterruptedException | ExecutionException ex) {
						System.err.println(ex);
					}
				}
			} else {
				System.out.println("无法打开异步服务器套接字通道!");
			}
		} catch (IOException ex) {
			System.err.println(ex);
		}
	}
}
